package com.otaku.crawler.parser;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.otaku.crawler.model.WAHTPojo;
import com.otaku.crawler.util.EmailHelper;

public class WAHTParser {
	private static final Logger log = Logger.getRootLogger();
	
	private static final String MON_IDEN = "masonryBrick displaynone";
	private static final String PER_CON_IDEN = "perContentBox";
	
	public static List<WAHTPojo> parse(Document d) throws Exception{
		//return list
		List<WAHTPojo> rl = new ArrayList<WAHTPojo>();
		
		//enum all the interested div
		Elements mason = d.select("div[class="+MON_IDEN+"]");
		Elements perContent = d.select("div."+PER_CON_IDEN);
		
		if(mason != null && mason.size()>0){
			for(int i=0;i<mason.size();i++){
				Element e = mason.get(i);
				
				try {
					Elements imgs = d.select("div.blPic");
					if(imgs==null || imgs.size()==0) continue;
					
					Element imgE = imgs.first();
					String imgUrl = imgE.select("img[src]").first().attr("src");
					String url = imgE.select("a[href]").first().attr("href");
					
					String name = d.select("a[class="+"mB10 blTitle"+"]").first().text().trim();
					String info = d.select("div[class="+"blInfo mB10"+"]").first().ownText().trim();
					String time = d.select("div.blTime").first().text().trim();
					
					rl.add(new WAHTPojo(name, imgUrl, url, time, info));
				} catch (NullPointerException e1) {
					log.error("EXCEPTION:"+e.toString(), e1);
					e1.printStackTrace();
					continue;
				}
			}
		}
		
		if(perContent != null && perContent.size()>0){
			for(int i = 0;i<perContent.size();i++){
				Element e = perContent.get(i);
				
				try {
					Elements urls = e.select("div.con_title");
					if(urls==null || urls.size()==0 || urls.select("a[href]").size()==0) continue;
					Element urlE = urls.first().select("a[href]").first();
					String name = urlE.text().trim();
					String url = urlE.attr("href");

					String imgUrl = e.select("div.pro_img").first().select("img[src]").first().attr("src");
					Elements times = e.select("div.conTime");
					if(times==null ||times.size()==0) continue;
					String time = times.first().text().trim();
					String info = e.select("div.leftShowInfo").first().text().trim();
					
					rl.add(new WAHTPojo(name, imgUrl, url, time, info));
				} catch (NullPointerException e1) {
					log.error("EXCEPTION:"+e.toString(), e1);
					e1.printStackTrace();
					continue;
				}
				
			}
		}
		
		return rl;
	}
}
